//
//  SWMusicsListViewController.swift
//  ChildStory
//
//  Created by linhan on 2016/12/6.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWMusicsListViewController: SWBaseViewController,UITableViewDataSource,UITableViewDelegate,SWAPIComponent,ScrollTabBarDelegate
{
    private class MusicCategory:NSObject
    {
        var name:String = ""
        var categoryID:Int = 0
        var musics:[SWMusic] = []
        
        init(response:SWMusicCategoryRsp)
        {
            name = response.name ?? ""
            categoryID = response.categoryID ?? 0
        }
    }
    
    private var _categoryIndex:Int = 0
    private var _list:[MusicCategory] = []
    
    private var _tabBar:ScrollTabBar?
    lazy private var _tableView:UITableView = UITableView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    deinit
    {
        trace("DEINIT SWMusicsListViewController")
    }
    
    private func setup()
    {
        title = "乐库"
        automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = UIColor.white
        let lineColor:UIColor = UIColor(hex: 0xe1e1e1)
        
        _tabBar = ScrollTabBar(frame: CGRectMake(0, navigationBarBottom, view.width, 40))
        _tabBar?.font = UIFont.systemFont(ofSize: 14)
        _tabBar?.itemSpacing = 30
        _tabBar?.alignment = .left
        _tabBar?.selectedColor = UIColor(hex: 0x2f3231)
        _tabBar?.unselectedColor = UIColor(hex: 0xababab)
        _tabBar?.delegate = self
        view.addSubview(_tabBar!)
        
        let separatorLine1:UIView = UIView()
        separatorLine1.frame = CGRectMake(0, _tabBar?.bottom ?? 0, view.width, 1)
        separatorLine1.backgroundColor = lineColor
        view.addSubview(separatorLine1)
        
        let headerView:UIView = UIView()
        headerView.frame = CGRectMake(0, 0, view.width, 50)
        headerView.backgroundColor = UIColor.white
        view.addSubview(headerView)
        
        let icon:UIImageView = UIImageView(image:UIImage(named:"musics_icon_music"))
        icon.center = CGPointMake(28, headerView.height * 0.5)
        headerView.addSubview(icon)
        
        let label:UILabel = UILabel()
        label.font = UIFont.systemFont(ofSize: 17)
        label.textColor = UIColor(hex: 0x2f3231)
        label.text = "推荐音乐"
        label.sizeToFit()
        label.center = CGPointMake(icon.right + 15 + label.width * 0.5, icon.center.y)
        headerView.addSubview(label)
        
        let separatorLine2:UIView = UIView()
        separatorLine2.frame = CGRectMake(0, headerView.height - 1, view.width, 1)
        separatorLine2.backgroundColor = lineColor
        headerView.addSubview(separatorLine2)
        
        let tableY:CGFloat = separatorLine1.bottom
        _tableView.frame = CGRectMake(0, tableY, view.width, view.height - tableY)
        _tableView.backgroundColor = UIColor.white
        _tableView.tableFooterView = UIView()
        _tableView.tableHeaderView = headerView
        _tableView.dataSource = self
        _tableView.delegate = self
        _tableView.separatorColor = lineColor
        _tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15)
        _tableView.rowHeight = 60
        //_tableView.layoutMargins = UIEdgeInsetsMake(0, 15, 0, 15)
        view.addSubview(_tableView)
        
        loadData()
    }
    
    private func loadData()
    {
        let req = SWMusicCategoryFetchReq()
        req.successCallback = {[weak self] response,cache in
            if let response = response as? SWMusicCategoryFetchRsp,
               let categories = response.categories, categories.count > 0
            {
                let items:[String] = categories.map({$0.name ?? ""})
                let aCategories:[MusicCategory] = categories.map({MusicCategory(response: $0)})
                self?._list = aCategories
                self?._tabBar?.titleItems = items
                self?._tabBar?.selectedIndex = 0
                
                if let category = aCategories.valueAt(0)
                {
                    self?.loadMusics(categoryID: category.categoryID)
                }
            }
        }
        req.failCallback = {error in
        
        }
        load(req)
    }
    
    private func loadMusics(categoryID:Int)
    {
        let req = SWMusicsFetchReq()
        req.index = 0
        req.count = 100
        req.categoryID = categoryID
        req.successCallback = {[weak self] response,cache in
            if let response = response as? SWMusicsFetchRsp,
                let musics = response.musics, musics.count > 0
            {
                let aMusics:[SWMusic] = musics.flatMap({SWMusic(response:$0)})
                self?._list.filter({$0.categoryID == categoryID}).valueAt(0)?.musics += aMusics
                
                self?._tableView.reloadData()
            }
        }
        req.failCallback = {error in
            
        }
        load(req)
    }
    
    //MARK ============================================================================================
    //==============================         UITableViewDelegate        ===============================
    //=================================================================================================
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return _list.valueAt(_categoryIndex)?.musics.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let index:Int = indexPath.row
        var cell:UITableViewCell?
        let identifier:String = "SWGeneralMusicCell"
        cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        if cell == nil
        {
            cell = SWGeneralMusicCell(style: .default, reuseIdentifier: identifier, cellWidth: view.width)
            //(cell as? SWFeedFlowCell)?.delegate = self
        }
        (cell as? SWGeneralMusicCell)?.music = _list.valueAt(_categoryIndex)?.musics.valueAt(index)
        return cell ?? UITableViewCell(style: .default, reuseIdentifier: "")
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        tableView.deselectRow(at: indexPath, animated: false)
        
        if let musics = _list.valueAt(_categoryIndex)?.musics, musics.count > 0
        {
            let viewController = SWEventMusicViewController()
            viewController.musics = musics
            viewController.index = indexPath.row
            navigationController?.pushViewController(viewController, animated: true)
        }
    }
    
    
    //MARK ================================= ScrollTabBarDelegate =========================
    func scrollTabBar(_ tabBar: ScrollTabBar, didSelectIndex index: Int)
    {
        _categoryIndex = index
        if let category = _list.valueAt(_categoryIndex)
        {
            if category.musics.count > 0
            {
                _tableView.reloadData()
            }
            else
            {
                loadMusics(categoryID: category.categoryID)
            }
        }
    }
    
    
    
}
